using System;
using System.Collections.Generic;
using AutoTest.Core.Infrastructure.Messaging;

namespace AutoTest.Core.Domain.DuplicateFileChangeSuppression
{
    public class DuplicateFileChangeSuppressor : IDuplicateFileChangeSuppressor, IInterceptorOf<FileChangedMessage>
    {
        private static readonly TimeSpan IgnoreDuplicatesTimeout = TimeSpan.FromSeconds(0.5);

        private readonly Dictionary<FileChangedMessage, DateTime> _received = new Dictionary<FileChangedMessage, DateTime>();
        private readonly IMessageBus _messageBus;

        public DuplicateFileChangeSuppressor(IMessageBus messageBus)
        {
            _messageBus = messageBus;
        }

        public void Intercept(FileChangedMessage message)
        {
            if (_received.ContainsKey(message) && (DateTime.Now - _received[message]) < IgnoreDuplicatesTimeout)
                return;

            _received[message] = DateTime.Now;

            _messageBus.Publish(this, message);
        }
    }
}